﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PHMEE.ConsoleTools;
using Serilog;
using Serilog.Events;

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
#if DEBUG
    .MinimumLevel.Override("PHMEE", LogEventLevel.Debug)
#else
                .MinimumLevel.Override("PHMEE", LogEventLevel.Information)
#endif
    .Enrich.FromLogContext()
    .WriteTo.Async(c => c.File("Logs/logs-.txt", rollingInterval: RollingInterval.Day))
    .WriteTo.Async(c => c.Console())
    .CreateLogger();

try
{
    var host = CreateHostBuilder(args).Build();

    await host.StartAsync();
    
    // 获取 CommandLineService 并运行
    await host.Services.GetRequiredService<CommandLineService>().RunAsync();
    
    await host.StopAsync();
}
catch (OperationCanceledException)
{
    // 忽略取消操作导致的异常
    Log.Information("应用程序正常退出");
}
catch (Exception ex)
{
    Log.Fatal(ex, "应用程序异常终止！");
}
finally
{
    Log.CloseAndFlush();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseAutofac()
        .AddAppSettingsSecretsJson()
        .ConfigureLogging((context, logging) =>
        {
            logging.ClearProviders();
            logging.AddSerilog(Log.Logger);
        })
        .ConfigureServices((hostContext, services) =>
        {
            services.AddApplication<PHMEEConsoleToolsModule>();
            
            services.AddTransient<CommandLineService>();
        });